<?php
/**
 * Created by PhpStorm.
 * User: jocky
 * Date: 29/08/2017
 * Time: 17:36
 */
namespace frontend\controllers;

use common\models\ar\User;
use common\models\ar\UserTrade;
use common\models\Common;
use common\models\Sms;
use frontend\models\LoginForm;
use frontend\models\OnlyCaptchaValidate;
use yii\web\Controller;
use yii\web\Cookie;
use common\models\ar\UserBrokers;
use common\models\ar\UserMoney;
use common\models\ar\Changecache;
class RegController extends Controller
{
    public $layout = 'common-out';

    public function actions()
    {
        return [
            'captcha' => [
                'class' => 'common\actions\CaptchaAction',
                'minLength' => 4,
                'maxLength' => 4,
                'transparent' => true,
                'offset' => 15,
                'foreColor' => 0x04a9f4,
                'backColor' => 0x000000,
                'height' => 50
            ],
        ];
    }

    public function actionIndex()
    {
        $req = \Yii::$app->request;
        $res = \Yii::$app->response;
        $brokerId = trim($req->get('field＿name', ''));
        if (!$brokerId) {
            //从cookie中查看是否有记录
            $brokerId = $req->cookies->getValue('brokerId', '');
        }

        $pObj = User::find()->where(['loginName' =>$brokerId])->one();
        if ($pObj && $pObj->login_flag != 1) {
            //将推荐码保存到cookie中，防止页面跳转时不能正确识别来源
            $cookie = new Cookie([
                'name' => 'brokerId',
                'value' => $brokerId,
                'expire' => time() + 5 * 60,//保留5分钟,
                'httpOnly' => true,
            ]);
            $res->cookies->add($cookie);
        } else {
            //输入了不存在的推荐码，删除
            $res->cookies->remove('brokerId');
            //将推荐码置为空
            $brokerId = '';
        }

        return $this->render('index', ['brokerId' => $brokerId]);
    }

    public function actionSubmit()
    {
//        $agentID = '0';
//        $levelId = '01';
        $req = \Yii::$app->request;
        if ($req->post('field＿name')){
            $agentID = $req->post('field＿name');
            $userBrokers = UserBrokers::find()->where(['id' => $agentID])->one();
            if ($userBrokers){
                $agentID = $userBrokers['id'];
                $levelId = $userBrokers['level'];
                }
        }
        else
        {
            $code = trim($req->post("code", ''));
            if (empty($code)) {
                $code = 1001;
                $msg = "请输入邀请码";
                exit(json_encode(['code' => $code, 'msg' => $msg]));
            }
            $codes=UserBrokers::findOne(["id"=>$code]);
            if (!$codes){
                $code = 1001;
                $msg = "您输入邀请码不存在";
                exit(json_encode(['code' => $code, 'msg' => $msg]));
            }else{
                $levelId=$codes['level'];
                $agentID = $codes['id'];
            }
        }
////        echo "get brokerId=";
//        var_dump($agentID);
//        echo "get level";
//        var_dump($levelId);
//        //exit();

        $alias = trim($req->post("alias", ''));
        if (mb_strlen($alias) < 2) {
            $code = 1001;
            $msg = "请输入您的真实姓名";
            exit(json_encode(['code' => $code, 'msg' => $msg]));
        }
        $captcha = trim(\Yii::$app->request->post('captcha', ''));

        $validate = new OnlyCaptchaValidate();
        $validate->controller = 'reg';
        $validate->captcha = $captcha;

        if (!$validate->validate()) {
            exit(json_encode(['code' => 1001, 'msg' => "验证码不正确 "]));
        }

        // $number = trim($req->post("number", ''));
//        var_dump(mb_strlen($number) < 2 && !is_numeric($number));
//        exit();
        // if (mb_strlen($number) < 2 && !is_numeric($number)) {
        //     $code = 1010;
        //     $msg = "请输入数字编号，范围在（00001-10000）";
        //     exit(json_encode(['code' => $code, 'msg' => $msg]));
        // }

//        $password = trim($req->post("password", ''));
//        if (strlen($password) < 6) {
//            $code = 1003;
//            $msg = '密码长度不能小于6位';
//            exit(json_encode(['code' => $code, 'msg' => $msg]));
//        }

//        $cellphone = trim($req->post("cellphone", ''));
//        $check = Common::dataCheck($cellphone, [
//            'type' => 3,
//            'detail' => [
//                'pattern' => '/^1[34578][0-9]{9}$/',
//                'info' => '手机号码不正确'
//            ],
//        ]);
//        if ($check['code'] != 1) {
//            $code = 1005;
//            $msg = $check['msg'];
//            exit(json_encode(['code' => $code, 'msg' => $msg]));
//        }

        //一个手机号只能绑定一个账号
//        $obj = UserTrade::find()->where(['cellphone' => $cellphone])->one();
//        if ($obj) {
//            $code = 1005;
//            $msg = '手机号码已绑定';
//            exit(json_encode(['code' => $code, 'msg' => $msg]));
//        }

         $pObj = User::find()->where(['agentID' => $agentID])->one();
        //创建交易账户
        $time=date("Y-m-d H:i:s");
       if (strlen($levelId) < 2) {
           $num = str_pad($levelId, 2, "0", STR_PAD_LEFT);
       }else{
           $num=$levelId;
       }
        $clientSN ='12464';
        $clientSN ="8{$num}{$clientSN}";
        $clientLike = "8{$num}%";
//        var_dump($clientSN);
//        exit();
        $userTmp = "SELECT `loginName` FROM `user` WHERE loginName like '".$clientLike."' ORDER BY `loginName` DESC LIMIT 1";
        $userTmp = User::findBySql($userTmp)->one();
        if($userTmp)
        {
            $clientSN=(string)($userTmp['loginName']+1);
        }
        try{
            $users=new User();
            $users->loginName = $clientSN;
            $users->loginpsw ="666666";
            $users->accountName = $alias;
            $users->userType = 1001;
            $users->address ="";
            $users->RegisterDate = $time;
            $users->line_waring = 60;
            $users-> line_LimitOpen = 100;
            $users-> line_ForceClose =50 ;
            $users-> hedgeStrategy = 5;
            $users->limit_openorder = 0;
            $users->agentID=$agentID;
            $users-> login_flag= 2;
            $users->templatePtId=0;
            $users->save(false);
            //查找id并将ID写入到change_caches
            $UserIDs=User::find()->where(['loginName'=>$clientSN])->one();
            $Changecaches = new Changecache;
            $Changecaches->userid=$UserIDs['userID'];
            $Changecaches->change_type=1;
            $Changecaches->save();
            //ID写入到user_money,初始化资金表
            $userMoney= new UserMoney();
            $userMoney->userID=$UserIDs['userID'];
            $userMoney->totalMoney=0;
            $userMoney->userDeposit=0;
            $userMoney->equip=0;
            $userMoney->save();
            if ($users->save(false)){
                $code = 1;
                $msg = "创建成功";

                //登录的账户名保存到cookie中
                setcookie("login_clientSN", $clientSN, time() + 7 * 24 * 3600, '/');
                //主动登录一次
                $model = new LoginForm();
                $model->captchaFlag = false;
                $model->username = $clientSN;
                $model->password = "666666";
                $model->validate() && $model->login();
            }else{
                $code = 0;
                $msg = "创建失败";
            }
            //$bool = UserDao::addTrader(0, $usersID, $attr, $req->userIP, $req->userAgent);
        }
        catch(Exception $e){
                $code = 0;
                $msg = "创建失败";
        }
        exit(json_encode(['code' => $code, 'msg' => $msg]));
    }

    /**
     * 发送短信
     */
    public function actionSendSms()
    {
        return 1;
        exit();
        $cellphone = trim(\Yii::$app->request->get('cellphone', ''));
        $captcha = trim(\Yii::$app->request->get('captcha', ''));

        $validate = new OnlyCaptchaValidate();
        $validate->controller = 'reg';
        $validate->captcha = $captcha;

        if (!$validate->validate()) {
            exit(json_encode(['code' => 1001, 'msg' => "验证码不正确 "]));
        }

        $check = Common::dataCheck($cellphone, [
            'type' => 3,
            'detail' => [
                'pattern' => '/^1[34578][0-9]{9}$/',
                'info' => '手机号码不正确'
            ],
        ]);
        if ($check['code'] != 1) {
            $code = 1001;
            $msg = $check['msg'];
            exit(json_encode(['code' => $code, 'msg' => $msg]));
        }

        //一个手机号只能绑定一个账号
        $isExist = UserTrade::find()->where(['cellphone' => $cellphone])->count();
        if ($isExist) {
            $code = 1002;
            $msg = '手机号码已绑定';
            exit(json_encode(['code' => $code, 'msg' => $msg]));
        }

        $return = Sms::send($cellphone, 1);
        exit(json_encode($return));
    }

    /**
     * 注册信息显示
     */
    public function actionInfo()
    {
        if (\Yii::$app->user->isGuest) {
            return $this->redirect('/login');
        }
        $uid = \Yii::$app->user->id;
        $userObj = UserTrade::findOne($uid);
        return $this->render('info', ['info' => $userObj]);
    }
}